import spec_md_api
from rqalpha.api import *
from rqalpha.utils.logger import user_log, system_log
import numpy as np
import unittest
from rqalpha.model.order import Order
from spec_md_api.trade_api import *

'''
ma5>ma20 做多，否则做空
测试用例：每次开平仓后查询持仓信息是否正确
'''

static_param = {"future_vol": 1, "stock_amount": 200000,"stock_shares":200,"stock_lots":5,"slippage":3,"unit":0.01}
dynamic_param = {"main_contract": None,
                 "last_main_contract": None, "is_switch": False}


def init(context):
    """
    context内引入全局变量s1，存储目标合约信息
    :param context: 策略上下文
    :return:
    """
    user_log.info("init")
    context.stock_symbol = '600489.SH'
    subscribe(context.stock_symbol)
    subscribe_event(EVENT.TRADE, handle_trader)
    context.trade_list = []
    context.position = 0 # 初始仓位为0
    print("上下文：",context.run_info.run_type)
    print("实例id:",context.config.mod.pyspec.strat_inst_id)


def before_trading(context):
    pass


def handle_bar(context, bar_dict):
    """
    :param context: 策略上下文
    :param bar_dict: 当前合约池内所有合约的bar数据信息都会更新在bar_dict里面
    :return:
    """
    bar_datetime = bar_dict.dt
    if context.run_info.run_type == RUN_TYPE.PAPER_TRADING:
        #print("在线预期持仓：", context.position, "，在线实际持仓：", query_real_positions(symbol=context.stock_symbol,direction=POSITION_DIRECTION.LONG))
        actual_position = get_position(strat_inst_id = context.config.mod.pyspec.strat_inst_id)
        print("在线预期持仓：", context.position, "，在线实际持仓：", actual_position)

    close: np.ndarray = history_bars(context.stock_symbol, 20, "1m", ['close'],adjust_type = "none")
    if len(close) < 20:
        return
    if close[-5:].mean() > close.mean():
        buy_stock(context)
    else:
        sell_stock(context)


def buy_stock(context):
    """
    买入股票：buy_stock(context)
    :param context: 策略上下文
    :return:
    """
    qty = context.portfolio.positions[context.stock_symbol].quantity
    if qty <= 0:
        buy_order_1 = order_value(context.stock_symbol, static_param["stock_amount"])
        user_log.info("按价值开仓={}".format(buy_order_1))


def sell_stock(context):
    """
    卖出股票：sell_stock(context)
    :param context: 策略上下文
    :return:
    """
    qty = context.portfolio.positions[context.stock_symbol].sellable
    if qty > 0:
        # 指定价值平仓
        sell_order_2 = order_target_value(context.stock_symbol, 0)
        user_log.info("指定价值平仓={}".format(sell_order_2))


def handle_trader(context, trader):
    """
    收到成交信息，将其添加到list中
    handle_trader(context, trader)
    :param context: 策略上下文
    :param trader: 交易
    :return:
    """
    context.trade_list.append(trader)
    user_log.info("成交信息={}".format(trader.trade))
    if(trader.trade.side == SIDE.BUY):
        context.position = context.position + trader.trade.last_quantity
    else:
        context.position = context.position - trader.trade.last_quantity
    actual_position = context.portfolio.positions[context.stock_symbol].quantity

    print("预期持仓：",context.position,"，实际持仓：",actual_position)

